package com.xbf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbf.entity.Goods;
import com.xbf.entity.Order;
import com.xbf.mapper.OrderMapper;
import com.xbf.service.GoodsService;
import com.xbf.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private GoodsService goodsService;

    @Override
    @Transactional
    public boolean createOrder(Order order) {
        // 减少库存
        boolean stockReduced = goodsService.reduceStock(order.getGId(), order.getONum());
        if (!stockReduced) {
            return false;
        }
        // 设置订单时间
        order.setOTime(new Date());
        // 保存订单
        return save(order);
    }

    @Override
    public List<Order> getOrdersByUserId(Integer userId) {
        // 获取订单列表
        List<Order> orders = lambdaQuery()
                .eq(Order::getUId, userId)
                .list();

        // 为每个订单添加商品信息
        orders.forEach(order -> {
            Goods goods = goodsService.getById(order.getGId());
            if (goods != null) {
                order.setGName(goods.getGName());
                order.setGPrice(goods.getGPrice());
            }
        });

        return orders;
    }
}
